<?php
/**
 * Created by PhpStorm.
 * User: chenguangpeng
 * Date: 15-7-22
 * Time: 上午9:24
 * 票付通资源库
 */

namespace PFT;

class Resource {

    private $db;

    public function __construct(\PDO $db=null)
    {
        $this->db = $db;
    }

    /**
     * 统计不同类型产品的数量
     *
     * @return array
     */
    public function CountProduct()
    {
        $sql  = "SELECT COUNT(*) AS cnt,p_type FROM pft_resource WHERE verify_status<2 GROUP BY p_type";
        $stmt = $this->db->prepare($sql);
        $data = array(
            'A'=>0,'B'=>0,'C'=>0,'D'=>0
        );
        $stmt->execute();
        while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
            $data[$row['p_type']] = $row['cnt'];
        }
        return $data;
    }

    /**
     * 资源库展示
     *
     * @param array $params
     * @param bool $getTotal
     * @param int $offset
     * @param int $limit
     * @return array|string
     */
    public function show(Array $params, $getTotal=false, $offset=0, $limit=10)
    {
        $where = '1=1 AND verify_status<2';
        $search = array();
        foreach($params as $key => $val){
            /*
            if($key=='d_province'){
                $sql = "select n_code from pft_area_code_concat where parent_province=?";
                $stmt = $this->db->prepare($sql);
                $stmt->execute(array($val));
                $where_province = '';
                while($row=$stmt->fetch(\PDO::FETCH_ASSOC)){
                    $where_province .= $row['n_code'].',';
                }
                $where_province = rtrim($where_province,',');
                $where .= " AND areacode in($where_province)";
            */
            if($key=='area'){
                $where      .= " AND $key like'$val%' ";
            }elseif($key=='title'){
                $where .= " AND title like '%$val%'";
            }elseif($key=='jtype'){
                $where .= " AND jtype in('$val','".$val."A')";
            }else{
                $where      .= " AND $key=?";
                $search[]    = $val;
            }
        }
        if ($getTotal===true) {
            $sql = "SELECT COUNT(*) FROM pft_resource WHERE $where";
            $stmt = $this->db->prepare($sql);
            $stmt->execute($search);
            return $stmt->fetchColumn(0);
        }
        $sql = "SELECT * FROM pft_resource WHERE $where order by id desc LIMIT $offset, $limit";
        $stmt = $this->db->prepare($sql);
        $stmt->execute($search);
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    /**
     * 保存资源信息
     *
     * @return array|bool
     */
    public function SaveResource()
    {
        $update_id = intval($_POST['update_id']);
        $where = '';
        if ($update_id) {
            $where = " AND id <> $update_id";
        }
        //检测是否存在相同的产品名称
        $title = \safetxt($_POST['title']);
        $strChkTitle = "SELECT id FROM pft_resource WHERE title='$title' $where AND verify_status<2  LIMIT 1";
        $stmt = $this->db->prepare($strChkTitle);
        $stmt->execute();
        if ($stmt->fetchColumn(0)) {
            return array('code'=>401, 'msg'=>"资源【{$title}】已存在");
        }
        $p_type = \safetxt($_POST['ptype']);
        if (!in_array($p_type, array('A','B','C','D','F'))) {
            return array('code'=>401, 'msg'=>"类型错误");
        }
        $tel    = \safetxt($_POST['tel']);
        $jtype  = \safetxt($_POST['jtype']);
        $address= \safetxt($_POST['address']);
        $runtime= \safetxt($_POST['runtime']);
        $jtzn   = \safehtml($_POST['jtzn']);
        $jdjj   = \safehtml($_POST['jdjj']);
        $bhjq   = \safehtml($_POST['bhjq']);
        $jqts   = \safehtml($_POST['jqts']);
        $apply_did = \safehtml($_POST['apply_did']);
        $verify_status = $_SESSION['sid']==1 ? 1 : 0;
        $topic  = str_replace('，',',',\safetxt($_POST['topic']));
        $lng_lat_pos = explode(',',$_POST['lng_lat_pos']);
        $lng    = $lng_lat_pos[0];
        $lat    = $lng_lat_pos[1];
        $lng_lat_pos    = "{$lng},{$lat}";
        $addtime= date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);

        $competitor= intval($_POST['competitor']);
        $ticket_system= intval($_POST['ticket_system']);
        $terminal= intval($_POST['terminal']);

        $province = intval($_POST['d_province']);
        $city     = intval($_POST['d_city']);
        $code     = "{$province}|{$city}|0";
//        $s_code=explode('|',$code);
        if($province==1||$province==2||$province==3||$province==4
            ||$province==32||$province==33 ||$province==34){
            //32 香港 33 澳门 34 台湾
            $code=$province.'|1|0';
        }

        //添加区域代码
        $sql="select n_code from pft_area_code_concat where s_code='$code' limit 1";
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $areacode       = $stmt->fetchColumn(0);

        $imgpathGrp     =  implode(',', $_POST['imgpathGrp']);


        if ($update_id) {

            //修改已关联的景区的信息          等级,  旧区域码,   新区域码,     地址,      主题,        经纬,          开放时间
            $sql = "update uu_land set `jtype`=?,`area`=?,`areacode`=?,`address`=?,`topic`=?,`lng_lat_pos`=?,`runtime`=?
                    where resourceID=$update_id order by id desc limit 10";
            $stmt = $this->db->prepare($sql);
            $query = array(
                $jtype,$code,$areacode, $address,$topic,$lng_lat_pos,$runtime
            );
            $stmt->execute($query);


            $run_sql = <<<SQL
        UPDATE pft_resource set `title`=?, `p_type`=?, `tel`=?, `jtype`=?, `area`=?,
        `areacode`=?, `address`=?, `runtime`=?, `jtzn`=?, `jdjj`=?, `bhjq`=?, `jqts`=?,
        `imgpathGrp`=?, `verify_status`=?, `topic`=?, `lng_lat_pos`=?,
        `competitor`=?,addtime=?,apply_did=?,ticket_system=?,terminal=? WHERE id=$update_id LIMIT 1
SQL;
        }
        else {
            $run_sql = <<<SQL
        INSERT INTO pft_resource(`title`, `p_type`, `tel`, `jtype`, `area`,
        `areacode`, `address`, `runtime`, `jtzn`, `jdjj`, `bhjq`, `jqts`,
        `imgpathGrp`, `verify_status`, `topic`, `lng_lat_pos`,
        `competitor`,addtime,apply_did,ticket_system,terminal) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
        ?, ?, ?, ?, ?, ?, ?, ?, ?)
SQL;
        }

        $stmt = $this->db->prepare($run_sql);
        $query = array(
            $title,$p_type,$tel,$jtype,$code,
            $areacode, $address,$runtime,$jtzn,$jdjj,$bhjq,
            $jqts, $imgpathGrp, $verify_status, $topic,
            $lng_lat_pos, $competitor, $addtime,$apply_did,$ticket_system,$terminal
        );

        return $stmt->execute($query);
//        $error = $stmt->errorInfo();

    }

    public function Set($id, $key, $val)
    {
        $sql = "UPDATE pft_resource SET `$key`=? WHERE id=? LIMIT 1";
        $stmt = $this->db->prepare($sql);
        return $stmt->execute(array($val, $id));
    }

    public function Rm($id)
    {
        $sql = "select id from uu_land where resourceID=? and status<3 limit 1";
        $stmt = $this->db->prepare($sql);
        $stmt->execute(array($id));
        $row = $stmt->fetch(\PDO::FETCH_ASSOC);
        if($row) return false;//需要删除产品后才能删除资源
        return $this->Set($id, 'verify_status', 3);
    }

    public function GetResourceByArea($province, $city)
    {
//        $province = intval($_GET['province']);
//        $city     = intval($_GET['city']);
//        $area = "{$province}|{$city}";
        $sql  = "SELECT id,title FROM pft_resource WHERE area LIKE '{$province}|{$city}%' AND verify_status<2";
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        return $data;
    }


    /**
     * 获取资源详情
     *
     * @param int $id 资源id
     * @return array
     * @throws \ErrorException
     */
    public function GetResourceInfo($id)
    {
        if (!is_numeric($id) || $id<=0) throw new \ErrorException('参数个数错误');
        $sql  = "SELECT * FROM pft_resource WHERE id=$id LIMIT 1";
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        $data = $stmt->fetch(\PDO::FETCH_ASSOC);
        if (!$data) throw new \ErrorException('该资源不存在');
        return $data;
    }
} 